import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

@Component
public class seckillTest1 {


    private static final String buyAndSell =
            " -- 参与秒杀的用户集合\n" +
                    " local join_key = KEYS[1]\n" +
                    " -- 库存\n" +
                    " local stock_key = KEYS[2]\n" +
                    " -- 当前用户 \n" +
                    " local uid = ARGV[1]\n" +
                    " -- 检查当前用户是否参与过这个活动\n" +
                    " local has_buy = redis.call('sismember', join_key, uid)\n" +
                    " -- 如果没有参与过\n" +
                    " if(tonumber(has_buy)==0) then\n" +
                    "     -- 预扣库存\n" +
                    "     local stock = redis.call('decr',stock_key) \n" +
                    "     -- 如果还有库存\n" +
                    "     if(tonumber(stock) >= 0) then\n" +
                    "         -- 将用户添加到已参加活动的集合中\n" +
                    "         redis.call('sadd', join_key, uid)\n" +
                    "         -- 返回 1 表示可以参加秒杀，后续进行订单处理\n" +
                    "         return 1\n" +
                    "     else\n" +
                    "         -- 返回 -1 表示因为没有库存不能参加秒杀\n" +
                    "         return -1\n" +
                    "     end\n" +
                    " else\n" +
                    "     -- 返回 -3 表示已经参与过活动\n" +
                    "     return -3\n" +
                    " end";
    @Autowired
    private static RedisTemplate redisTemplate;


    //秒杀活动初始化

    public static void init() {
        int hid = 1;
        Set keys = redisTemplate.keys("pbw*");
        redisTemplate.delete(keys);
        redisTemplate.opsForValue().set("pbw.stock_" + hid, 10);
        redisTemplate.opsForValue().set("pbw.sk.stock_" + hid, 10);
        redisTemplate.opsForSet().add("pbw.sk.hd_" + hid, 0);
    }

    public boolean buy(long hid, long uid) {
        System.out.println("user id=" + uid + "hid=" + hid);
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptText(buyAndSell);
        List<String> keys = Lists.newArrayList("pbw.sk.hd " + hid + "pbw.sk.stock " + hid);
        Long result = (Long) redisTemplate.execute(script, keys, uid);
        System.out.println("lua脚本的执行结果为:" + result);
        return result > 0;
    }


}
